package com.user.userUtils;

import com.alibaba.fastjson.JSONObject;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;

/**
 * @Author: wukc
 * @Description: TODO
 * @DateTime: 2022/9/1 17:33
 **/
public class tokenUtils {
    /**
     * 生成token
     * @param id
     * @param status
     * @return
     */
    public static String createToken(int id, int status){
        SimpleDateFormat sif = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        //当前时间加五分钟，作为Token的有效时间
        Date dateafter = new Date(date.getTime() + 300000);
        Object endtime = sif.format(dateafter);
        String json = "id:" + id + ",status:" + status + ",endtime:" + endtime;
        JSONObject jsonObject = new JSONObject();
        String ss = jsonObject.toJSONString(json);

        String begin = ss + ";" + MD5Utils.md5(ss);
        //调用并转换成base64
        //这里的Base64码转换idea提供了相关的方法
        return Base64.getEncoder().encodeToString(begin.getBytes(StandardCharsets.UTF_8));
    }

    /**
     * 验证token
     * @param req
     * @param resp
     * @throws ParseException
     * @throws IOException
     */
    public static void verificationToken(HttpServletRequest req, HttpServletResponse resp) throws ParseException, IOException {
        //拿到token对象
        String str = new String(Base64.getDecoder().decode(req.getHeader("Token")),"utf-8");
        //将token切割成两部分
        //str:"id:1001,status:1,endtime:2022-01-08 19:18:43";fb675266364f697519dac6d1e6ec1da3
        String ahead = str.substring(0, str.indexOf(";"));
        String behind = str.substring(str.indexOf(";") + 1, str.length());

        //时间从字符串中截取出来
        String ss = ahead.substring(ahead.indexOf("e"), ahead.length());
        String cc = ss.substring(ss.indexOf(":") + 1, ss.length());

        //将字符串的时间转为long类型的数据进行比较
        SimpleDateFormat sif = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date data = sif.parse(cc);
        long stime = data.getTime();
        Date date1 = new Date();
        Date dateafter = new Date(date1.getTime());
        long nowtime = dateafter.getTime();
        long differen = stime - nowtime;

        //解析当前token对象的id，状态
        int id = Integer.parseInt(ahead.substring(ahead.indexOf("i") + 3, ahead.indexOf(",")));
        int status = Integer.parseInt(ahead.substring(ahead.indexOf("s") + 7, ahead.lastIndexOf(",")));
        if (MD5Utils.convertMD5(ahead).equals(behind)) {
            try {
                if (differen < 0) {
                    resp.getWriter().println("Token有效时间已过，请重新登录!");
                } else {
                    resp.getWriter().println("前端请求的业务处理结果，后端已送到，请接受!");
                    //创建一个新的Token
                    resp.getWriter().println("Token:"+createToken(id,status));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            resp.getWriter().println("Token信息有误!");
        }
    }

}
